console.log("preload js loaded")

const fs = require("fs");

const os = require("os");

var path = require('path');

console.log('os', os)

console.log('fs', fs)


console.log('os.arch()', os.arch())

console.log('os.hostname()', os.hostname())

console.log('os.platform()', os.platform())

console.log('os.type()', os.type())


var cp = require("child_process");

console.log('cp', cp)

const { spawn } = require('child_process');

window.startNpc = function() {

  var exePath = path.resolve(__dirname, './npc.exe -server=nps.taotikee.com:8024 -vkey=onyo3olxjoaufigk');
  // var exePath = path.resolve(__dirname, './test.sh');
  console.log('exePath', exePath)
  var startChild = cp.exec(exePath,function(err,stdout,stderr){
    if(err){
      console.error(err);
    }
    console.log(startChild.pid); 
    console.log("stdout:",stdout)
    console.log("stderr:",stderr);
  });

  startChild.stdout.on('data', function(data) {
    console.log(data.toString()); 
  })

  console.log('startChild', startChild)

  console.log('startChild pid', startChild.pid)
}

window.getNpcPid =  function() {
  let allPid;
  var findChild = cp.exec('tasklist|findstr "npc.exe"',function(err,stdout,stderr){
    if(err){
      console.error(err);
    }
    console.log("stdout:",stdout)
    console.log("stderr:",stderr);
  })

  findChild.stdout.on('data', function(data) {
    console.log('getProcessPid data', data.toString().replace(/(.+\s+)(\d+)(\s\w+.+)/gm,'$2'));
    allPid =  data.toString().replace(/(.+\s+)(\d+)(\s\w+.+)/gm,'$2')
  })

  console.log('getProcessPid findChild', findChild); 
  return allPid;
}

window.resetNpc = function() {

  var exePath = path.resolve(__dirname, './npc.exe -server=nps.taotikee.com:8024 -vkey=0000');
  // var exePath = path.resolve(__dirname, './test.sh');

  console.log('exePath', exePath)
  cp.exec(exePath,function(err,stdout,stderr){
    if(err){
      console.error(err);
    }
    console.log("stdout:",stdout.toString())
    console.log("stderr:",stderr.toString());
  });
}

window.readConfig = function (data) {
  // const data = fs.readFileSync(path.resolve(__dirname,'./config.json'))
  // return data
  console.log('data', data)
  return data
}

window.stopNpc = function () {
  cp.exec('taskkill /f /t /im npc.exe',function(err,stdout,stderr){
    if(err){
      console.error(err.toString());
    }
    console.log("stdout:",stdout.toString())
    console.log("stderr:",stderr.toString());
  })
}

// utools 数据库修改
window.saveData = function(data) {
  console.log('saveData data', data)
  // 创建请求
  utools.db.put(data)
}

window.updateData = function() {

}

window.delData = function() {

}

window.getIdData = function(id) {
  return utools.db.get(id)
}

window.getDBData = function() {
  console.log('utools.db.allDocs()', utools.db.allDocs())
  return utools.db.allDocs()
}